import { createRouter, createWebHashHistory } from 'vue-router'

import { routes } from './routerList.js'
import useUserStore from '@/store/user.js'
import Role from '@/utils/role.js'

const Router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes
})

// 配置路由守卫
Router.beforeEach((to, from, next) => {
  // 如果普通用户访问管理员页面，跳转到首页
  if (useUserStore().userInfo === null || useUserStore().userInfo === undefined) {
    useUserStore().getUserInfo().then(() => {
      if (to.meta.role === 'admin' && useUserStore().userInfo?.role !== Role.ADMIN) {
        next({ path: '/403' })
      } else {
        next()
      }
    })
  } else {
    if (to.meta.role === 'admin' && useUserStore().userInfo?.role !== Role.ADMIN) {
      next({ path: '/403' })
    } else {
      next()
    }
  }
})

export default Router
